package com.woniu.zsd.commons.core;

import cn.hutool.jwt.JWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtil {
    //后续可修改成读取配置文件
    public final static String CIPHER = "d+XJ2ePVc6FlkcxqcHj4eyQt4RZur9LV6g6yY/WmjnE=";
    /**
     * @description: 创建token 注：要求存值时使用 map {"id":“asdasdfad","role":"ADMIN"}
     *                备选角色:ADMIN,CONTRACTOR,STORE,USER,PROJECT 管理/承接单位/商家/用户/维修人员
     * @params: [java.util.Map<java.lang.String, java.lang.Object>存入信息 , int 过期时间（秒）]
     * @return: java.lang.String token
     * @author: aheng
     * @time: 2025/3/27 16:00
     */
    public static String GenerateToken(Map<String, Object> claims, int expirationInSeconds) {
        return JWT.create().addPayloads(claims).setKey(CIPHER.getBytes()).setExpiresAt(new Date(System.currentTimeMillis() + expirationInSeconds * 1000L)).sign();
    }
    /**
     * @description: jwt解析器
     * @params: [java.lang.String]token
     * @return: java.util.Map<java.lang.String,java.lang.Object>  解析结果Map集
     * @author: aheng
     * @time: 2025/3/27 16:00
     */
    public static Map<String, Object> AnalyzeToken(String token) {
        try {
            //解析token
            return JWT.of(token).setKey(CIPHER.getBytes()).getPayloads();
        }//列出所有可能出现的异常
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * @description: 判断token是否正确
     * @params: [java.lang.String]
     * @return: boolean
     * @author: aheng
     * @time: 2025/3/28 15:29
     */
    public static boolean validateToken(String token) {
        try {
            JWT.of(token).setKey(CIPHER.getBytes()).getPayloads();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static void main(String[] args) {
        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("id", "1905533074310041600");
        System.out.println(JWTUtil.GenerateToken(objectObjectHashMap, 60 * 60 * 24 * 14));
    }
}
